<template>
  <el-dialog
    :draggable="true"
    :destroy-on-close="true"
    :model-value="checkDialog"
    :close-on-click-modal="false"
    title="新增服务项目"
    width="85%"
    top="8vh"
    class="check-dialog"
    @close="onCancel"
  >
    <div class="table">
      <el-table
        :border="true"
        stripe
        resizable
        height="450px"
        :data="tableDataList.feeDetails"
        :row-class-name="tableRowClassName"
        @cell-mouse-enter="onCellMouseEnter"
        @cell-mouse-leave="onCellMouseLeave"
      >
        <el-table-column label="操作" width="70" type="index" fixed="left" align="center">
          <template #default="scope">
            <div v-show="styleColumn[scope.$index].tableColumnIndex" :rowIndex="scope.$index">
              <span>{{ scope.$index + 1 }}</span>
            </div>
            <div v-show="styleColumn[scope.$index].tableColumnBtn">
              <span class="operation">
                <el-icon color="#007cff" size="16" class="icon" @click="addItem">
                  <CirclePlus />
                </el-icon>
                <el-icon
                  v-show="tableDataList.feeDetails.length > 1"
                  color="rgba(245, 108, 108, 1)"
                  size="16"
                  class="icon"
                  @click="deleteItem(scope.$index)"
                >
                  <RemoveFilled />
                </el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="结算类型" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.type" placeholder="结算类型" filterable clearable>
              <el-option
                v-for="item in options1"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="费用项目" width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-select
              v-model="scope.row.workFeeProjectId"
              placeholder="请选择"
              filterable
              clearable
              :remote-method="getworkFeeProjectPageSelect"
              :loading="loading"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="item in modules"
                :value="item.id"
                :label="item.name"
                @click="changeworkFeeProjectId(item, scope.$index)"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="申请数量" width="100">
          <template #default="scope">
            <el-input
              v-model.trim="scope.row.qty"
              placeholder="数量"
              @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价金额" width="120">
          <template #default="scope">
            <el-input
              v-model.trim="scope.row.price"
              clearable
              style="border-radius: 2px"
              @keyup="checkNum"
              @input="scope.row.price = scope.row.price.replace(/[^\d.]/g, '')"
            >
              <template #prepend>￥</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="总金额" width="120">
          <template #default="scope">
            <el-input disabled clearable :value="scope.row.price * scope.row.qty">
              <template #prepend>￥</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="备注" min-width="140" max-width="150">
          <template #default="scope">
            <el-input v-model.trim="scope.row.remark" clearable placeholder="填写备注" />
          </template>
        </el-table-column>
        <el-table-column label="附件(最多上传8个)" width="460">
          <template #default="scope">
            <div class="updata_pic">
              <div v-for="(img, index) in scope.row.images" class="disf_ipc">
                <img
                  v-if="img.image.replace(/.+\./, '') == 'pdf' || img.file?.type.includes('pdf')"
                  :src="pdf"
                  alt=""
                  style="width: 100%; cursor: pointer"
                />
                <img v-else class="img" :src="img.image" />
                <span class="item-actions">
                  <el-icon
                    color="#fff"
                    size="12"
                    class="item-preview"
                    @click="handlePictureCardPreview(img.image)"
                    ><zoom-in
                  /></el-icon>
                  <el-icon
                    size="12"
                    color="#fff"
                    class="item-delete"
                    @click="handleRemove(index, scope.$index)"
                  >
                    <Delete />
                  </el-icon>
                </span>
              </div>
              <el-upload
                action="#"
                multiple
                list-type="picture-card"
                accept="image/*,.pdf"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="
                  (file) => {
                    getProImages(file, scope.$index)
                  }
                "
              >
                <div class="plus_add">
                  <el-icon size="12">
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer_remark">
      <el-form-item label="审核备注" label-width="auto">
        <el-input
          v-model.trim="tableDataList.remark"
          class="w_input"
          type="textarea"
          size="small"
          show-word-limit
          maxlength="200"
          :autosize="{ minRows: 2, maxRows: 4 }"
          clearable
          placeholder="填写备注信息"
        />
      </el-form-item>
    </div>
    <div class="btns flex-justify-end">
      <el-button color="#007cff" style="width: 4vw" @click="onSaveBtn">提交申请</el-button>
      <el-button style="width: 3.2vw" @click="onCancel"> 取消 </el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="dialogVisible" draggable title="查看附件" top="8vh" width="70%">
    <iframe :src="`${dialogImageUrl}`" style="height: 660px; width: 100%" frameborder="0"></iframe>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, toRefs, reactive, onMounted, watch } from 'vue'
  import { feeSaveOrder, workFeeProjectPageSelect } from '../../../../../api/order'
  import { orderAnnexUpload } from '../../../../../api/upload'
  import pdf from '@/assets/image/pdf.png'
  import _ from 'lodash'
  import { ElMessage } from 'element-plus'
  import { checkNum } from '../../../../../utils/validate'
  const props = defineProps({
    checkDialog: Boolean,
    workId: [String, Array],
  })
  const { checkDialog, workId } = toRefs(props)
  const dialogVisible = ref(false)
  const dialogImageUrl = ref(null)
  const modules = ref(null)
  const loading = ref(false)
  const emits = defineEmits(['assign-dialog', 'update-list'])
  const styleColumn = ref([
    {
      tableColumnBtn: false,
      tableColumnIndex: true,
    },
  ])
  // 结算类型
  const options1 = [
    { name: '向部门收取', value: 1 },
    { name: '向部门支付', value: 2 },
    { name: '向公司收取', value: 3 },
    { name: '向公司支付', value: 4 },
  ]

  const tableDataList = reactive({
    id: null, //服务费用项目ID
    workId: null, //工单ID
    remark: '', //	审核备注
    feeDetails: [
      {
        delImageIds: [], //删除的工单费用图片对象ID
        id: null, //	费用项目详情ID，新增不必传，修改必传
        images: [],
        price: 0, //费用金额
        qty: 1, //数量
        updatePrice: false,
        remark: '', //备注
        status: 1, //审核状态 1-待审核，2-已通过，3-已驳回
        type: 1, //结算类型：1-向部门收取，2-向部门支付，3-向公司收取，4-向公司支付,示例值(1)
        workFeeProjectId: null, //工单费用项目ID
      },
    ],
  })

  // 给row对象赋索引值，注：在此赋值后，才可以在其他用到row的地址取值
  const tableRowClassName = ({ row, rowIndex }) => {
    row.index = rowIndex
  }
  // 鼠标移入事件
  const onCellMouseEnter = (row) => {
    styleColumn.value[row.index].tableColumnBtn = true
    styleColumn.value[row.index].tableColumnIndex = false
  }
  // 鼠标移出事件
  const onCellMouseLeave = (row) => {
    styleColumn.value[row.index].tableColumnBtn = false
    styleColumn.value[row.index].tableColumnIndex = true
  }

  // 添加
  function addItem() {
    let item = {
      delImageIds: [], //删除的工单费用图片对象ID
      id: null, //	费用项目详情ID，新增不必传，修改必传
      images: [],
      price: 0, //费用金额
      qty: 1, //数量
      updatePrice: false,
      remark: '', //备注
      status: 1, //审核状态 1-待审核，2-已通过，3-已驳回
      type: 1, //结算类型：1-向部门收取，2-向部门支付，3-向公司收取，4-向公司支付,示例值(1)
      workFeeProjectId: null, //工单费用项目ID
    }
    tableDataList.feeDetails.push(item)
    styleColumn.value.push({
      tableColumnIndex: true,
      tableColumnBtn: false,
    })
  }
  // 新增删除
  function deleteItem(n: number) {
    if (tableDataList.feeDetails.length == 1) {
      return
    }
    tableDataList.feeDetails = tableDataList.feeDetails.filter((o, index) => {
      return index != n
    })
    styleColumn.value.splice(n, 1)
  }
  // 保存
  async function onSaveBtn() {
    for (const key in tableDataList.feeDetails) {
      let imgobj = tableDataList.feeDetails[key]
      let arrimg = []
      if (imgobj.images.length > 0) {
        for (const i in imgobj.images) {
          arrimg.push(imgobj.images[i].file)
        }
        if (imgobj.images[0].file) {
          await orderAnnexUpload(arrimg).then((res) => {
            imgobj.images = res.data.data.rows.map((o) => ({ id: null, image: o }))
          })
        }
      }
    }
    tableDataList.workId = workId.value
    feeSaveOrder(tableDataList).then((res) => {
      if (res.data.success) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
          offset: 200,
        })
        emits('update-list')
        onCancel()
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
      }
    })
  }
  // 费用项目选择变化
  function changeworkFeeProjectId(item, index) {
    tableDataList.feeDetails[index].price = item.price
    tableDataList.feeDetails[index].updatePrice = item.updatePrice
  }
  // 费用项目下拉数据
  async function getworkFeeProjectPageSelect(val) {
    loading.value = true
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    await workFeeProjectPageSelect(data).then((res) => {
      if (res.data.success) {
        modules.value = res.data.data.rows
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
      }
      loading.value = false
    })
  }
  // 删除图片
  const handleRemove = (imgindex, index) => {
    tableDataList.feeDetails[index].images = tableDataList.feeDetails[index].images.filter(
      (o, i) => i != imgindex,
    )
  }
  // 查看图片
  const handlePictureCardPreview = (img) => {
    dialogImageUrl.value = img
    dialogVisible.value = true
  }
  //监听查看附件弹窗关闭时销毁 iframe内存
  watch(dialogVisible, (n) => {
    if (!n) {
      dialogImageUrl.value = 'about:blank'
    }
  })
  // 添加图片
  const getProImages = async (file, index) => {
    if (!['image/png', 'image/jpg', 'image/jpeg'].includes(file.raw.type)) {
      imgType()
      return
    }
    if (tableDataList.feeDetails[index].images.length >= 8) {
      onExceedNub()
      return
    }
    tableDataList.feeDetails[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
    })
  }
  const imgType = _.debounce(() => {
    ElMessage({
      type: 'error',
      message: '只能上传图片类型的文件',
    })
  }, 20)
  const onExceedNub = _.debounce(() => {
    ElMessage({
      showClose: true,
      message: '最多上传8个',
      type: 'error',
      duration: 2000,
    })
  }, 20)
  const onCancel = () => {
    emits('assign-dialog')
  }
  onMounted(() => {
    getworkFeeProjectPageSelect('')
  })
</script>

<style lang="scss" scoped>
  .top_no {
    padding-bottom: 8px;
    font-size: 12px;
    color: #999;
  }

  .operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      cursor: pointer;
      margin: 0 6px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }

  :deep(.el-table td.el-table__cell) {
    .el-input {
      .el-input-group__prepend {
        padding: 0 2px;
      }
    }
  }

  .btn_save {
    width: 60px;
  }

  .btn_cancel {
    width: 60px;

    &:hover {
      border: 1px solid #e5e5e5;
      color: #999;
      background-color: #e5e5e5;
    }
  }

  .footer_remark {
    margin-top: 20px;

    .w_input {
      width: 600px;
      margin-left: 10px;
      border-radius: 2px !important;
    }
  }

  :deep(.updata_pic) {
    display: flex;
    align-items: center;

    .el-upload {
      &.el-upload--picture-card {
        width: 40px;
        height: 40px;
      }
    }

    .disf_ipc {
      display: flex;
      width: 40px;
      height: 40px;
      position: relative;
      margin-right: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 2px;
      box-sizing: border-box;
      overflow: hidden;

      .img {
        width: 100%;
        position: absolute;
        border-radius: 2px;
      }

      .item-actions {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
      }

      &:hover .item-actions {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #7f7f7f9d;
        opacity: 1;
        border-radius: 2px;

        .item-preview {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }

        .item-delete {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }
      }
    }
  }
</style>
